<template>
  <!-- 自学模式 -->
  <div class="sbodyd">
    <!-- 图谱详情主体区域-->
    <div class="mainboxgj" v-if="lodings">
      <!-- 暂存数据
       zoomIn 放大
      zoomOut 缩小
      tdflag = true 拖动
      reset 重置
      -->

      <!-- 中央区域 左侧-->
      <div class="mainbottombox">
        <div class="maintopbox">
          <!-- 顶部画布区域 -->
          <div
            class="box"
            ref="box"
            id="canvasContainer"
            :style="{
              backgroundColor: atlasTypeName == '插画' ? '#ffff' : 'black',
            }"
          >
            <canvas
              id="myCanvas"
              :width="hbwidth / 2"
              :height="hbheight"
              :style="{
                cursor: myStyle,
                backgroundColor: atlasTypeName == '插画' ? '#ffff' : 'black',
              }"
              v-if="hbheight != 0"
            >
            </canvas>
            <div class="dctitlebox">
              <img src="@/images/dctitlebj.png" alt="" />
              <div class="dctitletext">MRI解剖矢状断层</div>
            </div>
            <div class="fjx"></div>
            <!--  marginLeft: hbwidth / 2, -->
            <canvas
              v-if="hbheight != 0"
              id="myCanvas2"
              :width="hbwidth / 2"
              :height="hbheight"
              :style="{
                cursor: myStyle,
              }"
            >
            </canvas>
            <div class="dctitlebox2 dctitlebox">
              <img src="@/images/dctitlebj.png" alt="" />
              <div class="dctitletext">人体解剖矢状断层</div>
            </div>
            <canvas
              v-show="isCanvasVisible"
              id="overlayCanvas"
              :width="hbwidth"
              :height="hbheight"
              ref="overlayCanvas"
              @touchstart="startDrawing"
              @touchend="stopDrawing"
              @touchmove="draws"
              @mousedown="startDrawing"
              @mouseup="stopDrawing"
              @mousemove="draws"
              @click="showTextInput"
              :style="{ cursor: currentCursorStyle }"
            >
            </canvas>
            <!-- <div class="overlayCanvastool" v-show="isCanvasVisible">
              <div>
                <input
                  id="size"
                  type="range"
                  min="1"
                  max="10"
                  v-model="brushSize"
                />
              </div>
            </div> -->
            <div
              v-if="showInput"
              :style="inputStyle"
              class="text-input-container"
            >
              <input
                v-model="customText"
                @keydown.enter="addTextMarkerOnEnter"
                class="text-input"
                placeholder="输入要添加的文字"
                @focus="isInputActive = true"
                @blur="handleInputBlur"
              />
            </div>
          </div>
          <!-- 底部常驻控制台 -->
          <div class="mainktbox">
            <div class="mainktitembox">
              <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'rectangle' }"
                @click="enableRectangleMode"
              >
                <img src="@/images/kt1.png" alt="" class="normal" />
                <img src="@/images/kt1ac.png" alt="" class="active" />
              </div>
              <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'circle' }"
                @click="enableCircleMode"
              >
                <img src="@/images/kt2.png" alt="" class="normal" />
                <img src="@/images/kt2ac.png" alt="" class="active" />
              </div>
              <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'arrow' }"
                @click="enableArrowMode"
              >
                <img src="@/images/kt3.png" alt="" class="normal" />
                <img src="@/images/kt3ac.png" alt="" class="active" />
              </div>
              <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'drawing' }"
                @click="enableDrawingMode"
              >
                <img src="@/images/kt4.png" alt="" class="normal" />
                <img src="@/images/kt4ac.png" alt="" class="active" />
              </div>
              <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'text' }"
                @click="enableTextMode"
              >
                <img src="@/images/kt5.png" alt="" class="normal" />
                <img src="@/images/kt5ac.png" alt="" class="active" />
              </div>
              <!-- <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'undo' }"
                @click="undo"
              >
                <img src="@/images/kt6.png" alt="" class="normal" />
                <img src="@/images/kt6ac.png" alt="" class="active" />
              </div> -->

              <!--    -->
              <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'zoom' }"
                @click="zoomIn"
              >
                <img src="@/images/kt7.png" alt="" class="normal" />
                <img src="@/images/kt7ac.png" alt="" class="active" />
              </div>
              <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'reset' }"
                @click="reset"
              >
                <img src="@/images/kt6.png" alt="" class="normal" />
                <img src="@/images/kt6ac.png" alt="" class="active" />
              </div>
              <!-- <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'reset' }"
                @click="reset"
              >
                <img src="@/images/kt8.png" alt="" class="normal" />
                <img src="@/images/kt8ac.png" alt="" class="active" />
              </div> -->
              <!-- <div
                class="mainktitem tool"
                :class="{ active: selectedTool === 'download' }"
                @click="downloadImage"
              >
                <img src="@/images/kt9.png" alt="" class="normal" />
                <img src="@/images/kt9ac.png" alt="" class="active" />
              </div> -->
            </div>
          </div>
        </div>
        <!-- 全新解刨菜单 -->
        <div class="jpmentbox divscroll">
          <div
            class="jpitem"
            v-for="(item, index) in mentdata"
            :key="item.markingPointsId"
            @click="taskjp(item)"
          >
            <div
              class="jpitemacive"
              :class="
                item.pointName == hoveredMarkerID ? 'jpitemacivehover' : ''
              "
            >
              {{ index + 1 }}、{{ item.pointName }}
            </div>
          </div>
        </div>

        <!-- 菜单右侧区域 
          pzfn 批注菜单 
          jubu() 局部标注标签
          downloadImage  下载保存
          undo 撤销
          redo 还原
          enableDrawingMode 绘制
          toggleEraser 橡皮擦
          changeimgclassfn('全部') 筛选扫描方向
            @click="changeimggroupfn('全部', true)" 加权
           @click="changeimgclassfn(item.classificationName)" v筛选扫描方向
             @click="changeimggroupfn(item.typeName, true)" 加权
             changecsd() 全部解剖部位
             @change="changecs(item)" 单个解剖部位
              :class="{ active: selectedTool === 'downloadImage' }"
                
选择颜色
                       <div class="tool mentbjacitemtool" style="position: relative">
                  <input
                    id="color"
                    type="color"
                    v-model="brushColor"
                    class="colorts"
                  />
                  <img src="@/images/m5.png" alt="" class="normal" />
                  <img src="@/images/m5ac.png" alt="" class="active" />
                </div>
                            选择粗细
                             <div
                  class="tool mentbjacitemtool"
                  style="position: relative"
                  @click="hbcshow = !hbcshow"
                >
                  <div class="hbcbox" v-if="hbcshow">
                    <div
                      class="hbcitem"
                      @click="(brushSize = item), (hbcshow = false)"
                      v-for="(item, index) in brushSizedata"
                      :style="{
                        border: item + 'px solid #ffffff',
                      }"
                      :key="index"
                    ></div>
                  </div>
                  <img src="@/images/m6.png" alt="" class="normal" />
                  <img src="@/images/m6ac.png" alt="" class="active" />
          
          事件-->
      </div>
    </div>

    <!-- 加载页 -->
    <div class="loader-container" v-if="loding">
      <div class="loader"></div>
      <p class="pd">加载中98%</p>
    </div>
  </div>
</template>

<script>
  // import {
  //
  //   getxqPoint 查询点位详情可以删除这里用不到了,
  //   getPointjs 查询富文本不用了,

  //
  // } from '@/api/atlas'
  import { debounce } from 'lodash';
  import { newdata } from '@/mixin/data';
  export default {
    //混入
    mixins: [newdata],
    data() {
      return {
        loding: false,
        lodings: false,
        medicineAtlasId: 23,
        atlasTypeName: '空客删除',
        box: null,
        markingPointsIdxz: '',
        optionsselect: [],
        hoveredMarkerID: 0,
        base: 'http://192.168.1.100',
        canvasHistory: [], // 添加画布历史记录数组
        redoHistory: [], // 添加重做历史记录数组
        state: {
          labels: null,
          showText: true,
          canBiaoZhu: false,
          pointColor: '#65FF00',
          pointSize: 7,
          imgScale: 1,
          zoomStep: 0.1,
          markers: [],
          markers2: [],
          canvas: null,
          ctx: null,
          rightimg: new Image(),
          img: new Image(),
          imgWidth: 480,
          imgHeight: 606,
          imgPosition: { x: 0, y: 0 },
          currentText: '',
          currentMarker: {},
          showLinesAndText: true,
          isDragging: false,
          startDragX: 0,
          startDragY: 0,
          imgOffsetX: 0,
          imgOffsetY: 0,
          isSpacePressed: false,
          hoveredMarker: null,
          editingMarker: false,
          editPanelX: 0,
          editPanelY: 0,
          addflag: false,
          flipHorizontal: false,
          flipVertical: false,
          rotation: 0,
          canvas2: null,
          ctx2: null,
        },
        markingPointsId: '',
        dcomid: Number(localStorage.getItem('dcomid')) || 1,

        visiblest: false,
        formModel: {
          userText: '',
        },
        bwstuddata: null,
        optionsdata: [
          { anatomicStructureName: '', flag: true, anatomicStructureId: '' },
        ],
        gosroll: null,
        jiegoudata: [],
        oneshow: false,
        startX: 0,
        startY: 0,
        isSwiping: false,
        startTime: 0,
        threshold: 30,
        fastSwipeThreshold: 200,
        fastSwipeDistance: 50,
        slowSwipeThreshold: 10,
        slowSwipeTimeThreshold: 200,
        isFastSwipe: false,
        hasMoved: false,
        tdflag: false,
        flag: false,
        hbheight: null,
        hbwidth: null,
        leftMarkers: [],
        rightMarkers: [],
        textModeEnabled: false,
        jubushow: false,
        pzshow: false,
        myStyle: 'inherit',
        context: null,
        overlayContext: null,
        isDrawing: false,
        isCanvasVisible: false,
        customText: '',
        showInput: false,
        inputStyle: {
          left: '',
          top: '',
          position: 'absolute',
        },
        isInputActive: false,
        currentMode: null,
        currentCursorStyle: 'inherit',
        brushColor: '#ff0000',
        brushSize: 2,
        isEraserMode: false,
        hbcshow: false,
        brushSizedata: [1, 2, 2.5, 3, 3.5, 4],
        allflag: true,
        classificationName: '全部',
        imggroupname: '全部',
        anatomicStructure: [
          {
            anatomicStructureName: '',
            flag: false,
            anatomicStructureId: '',
          },
        ],
        selectedTool: null, // 添加选中状态跟踪
        currentShape: null,
        mentdata: [],
      };
    },
    computed: {
      userdata() {
        return this.$store.state.user;
      },
    },
    created() {
      this.gettpxq();
    },
    mounted() {
      this.handleResize = debounce(this.handleResize, 200);
      window.addEventListener('resize', this.handleResize);

      // 添加键盘事件监听
      document.addEventListener('keydown', this.handleKeyDown);
      document.addEventListener('keyup', this.handleKeyUp);
    },
    beforeDestroy() {
      const canvas = document.getElementById('myCanvas');
      if (canvas) {
        canvas.removeEventListener('wheel', this.handleWheel);
      }
      const canvas2 = document.getElementById('myCanvas2');
      if (canvas2) {
        canvas2.removeEventListener('wheel', this.handleWheel);
      }
      window.removeEventListener('resize', this.handleResize);
      document.removeEventListener('keydown', this.handleKeyDown);
      document.removeEventListener('keyup', this.handleKeyUp);
    },
    methods: {
      // 初始化画布
      initCanvas(canvasId, isRightCanvas = false) {
        const canvas = document.getElementById(canvasId);
        if (!canvas) {
          console.warn('Canvas element not found');
          this.loding = false;
          return null;
        }

        const ctx = canvas.getContext('2d', { willReadFrequently: true });
        return { canvas, ctx };
      },

      // 添加事件监听
      addCanvasEventListeners(canvas) {
        if (!canvas) return;

        const events = [
          {
            name: 'wheel',
            handler: this.handleWheel,
            options: { passive: false },
          },
          { name: 'mousedown', handler: this.startDrag },
          { name: 'mousemove', handler: this.handleMouseMove },
          { name: 'mouseup', handler: this.stopDrag },
          { name: 'mouseleave', handler: this.stopDrag },
          { name: 'click', handler: this.handleCanvasClick },
          {
            name: 'touchstart',
            handler: this.handleTouchStart,
            options: { passive: false },
          },
          {
            name: 'touchmove',
            handler: this.handleTouchMove,
            options: { passive: false },
          },
          {
            name: 'touchend',
            handler: this.handleTouchEnd,
            options: { passive: false },
          },
        ];

        events.forEach(({ name, handler, options }) => {
          canvas.addEventListener(name, handler, options);
        });
      },

      // 加载图片
      loadImage(imgUrl, isRightCanvas = false) {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        // img.src = this.base + imgUrl;

        img.src = require('@/assets/atlaimg/' + imgUrl.replace(/^.*[\\/]/, ''));

        return new Promise((resolve, reject) => {
          img.onload = () => {
            if (!isRightCanvas) {
              this.state.imgWidth = img.naturalWidth;
              this.state.imgHeight = img.naturalHeight;
            }
            resolve(img);
          };
          img.onerror = (error) => {
            console.error('Failed to load image:', error);
            this.loding = false;
            reject(error);
          };
        });
      },

      // 处理标记点数据
      processMarkers(pointData, markersMap) {
        pointData.forEach((items) => {
          try {
            // 特殊处理数据格式
            // if (
            //   items.medicineAtlasImgId > 41893 ||
            //   items.medicineAtlasImgId < 41880
            // ) {
            //   return;
            // }
            if (items.medicineAtlasImgId != null) {
              const existingMarker = markersMap.get(items.medicineAtlasImgId);
              const markingPointsObjects = JSON.parse(items.markingPoints);

              // 设置标记点属性
              markingPointsObjects.medicineAtlasImgId =
                items.medicineAtlasImgId;

              // 处理每个标记点
              markingPointsObjects.bsdata.forEach((point, i) => {
                point.markingPointsId = items.markingPointsId;

                point.flag = true;
                point.labels = true;
                point.anatomicStructureName = items.anatomicStructureName;
                point.anatomicStructureId = items.anatomicStructureId;
                // console.log('当前', i);
              });

              if (existingMarker) {
                existingMarker.bsdata.push(...markingPointsObjects.bsdata);
              } else {
                markersMap.set(items.medicineAtlasImgId, markingPointsObjects);
              }
            }
          } catch (error) {
            console.error('Error processing item:', items, error);
          }
        });
        // 处理完成的

        // 根据 dcomid 升序排序，默认第一个是 41880
        Array.from(markersMap.values()).sort((a, b) => {
          // medicineAtlasImgId 可能是字符串，先转为数字
          const idA = Number(a.medicineAtlasImgId);
          const idB = Number(b.medicineAtlasImgId);
          if (idA === 41880) return -1;
          if (idB === 41880) return 1;
          return idA - idB;
        });

        // 给每个标记点设置 index
        markersMap.forEach((markerObj) => {
          if (Array.isArray(markerObj.bsdata)) {
            markerObj.bsdata.forEach((item, idx) => {
              item.index = idx + 1;
            });
          }
        });
        return Array.from(markersMap.values());
      },

      // 主函数优化
      async gettpxq() {
        this.loding = true;
        this.lodings = true;

        try {
          await this.$nextTick();

          if (!this.$refs.box) {
            console.warn('Box element not found');
            this.loding = false;
            return;
          }

          // 设置画布尺寸
          this.hbheight = this.$refs.box.offsetHeight;
          this.hbwidth = this.$refs.box.offsetWidth;
          // this.$nextTick(() => {
          //   this.hbheight = this.$refs.box.offsetHeight;
          //   this.hbwidth = this.$refs.box.offsetWidth;
          // });

          // 初始化左右画布
          const leftCanvas = this.initCanvas('myCanvas');
          const rightCanvas = this.initCanvas('myCanvas2', true);

          if (!leftCanvas || !rightCanvas) return;

          // 设置画布上下文
          this.state.canvas = leftCanvas.canvas;
          this.state.ctx = leftCanvas.ctx;
          this.state.canvas2 = rightCanvas.canvas;
          this.state.ctx2 = rightCanvas.ctx;

          // 加载图片
          const imgsrcd = this.imgsrc.find(
            (item) => item.medicineAtlasImgId == this.dcomid
          );
          const rightimgsrcd = this.rightimgsrc.find(
            (item) => item.medicineAtlasImgId == this.dcomid
          );
          const imgUrl = imgsrcd ? imgsrcd.imgUrl : this.imgsrc[0].imgUrl;
          const rightimgUrl = rightimgsrcd
            ? rightimgsrcd.imgUrl
            : this.rightimgsrc[0].imgUrl;

          if (!imgsrcd) {
            this.dcomid = this.imgsrc[0].medicineAtlasImgId;
          }

          // 加载左右画布的图片
          this.state.img = await this.loadImage(imgUrl);
          this.state.rightimg = await this.loadImage(rightimgUrl, true);

          // 添加事件监听
          this.addCanvasEventListeners(this.state.canvas);
          this.addCanvasEventListeners(this.state.canvas2);

          // 处理标记点数据
          this.state.markers = this.processMarkers(
            this.leftPointnewdata,
            new Map()
          );
          this.state.markers2 = this.processMarkers(
            this.rightPointnewdata,
            new Map()
          );
          console.log('处理玩的数据1', this.state.markers);
          console.log('处理玩的数2', this.state.markers2);

          // 处理解剖结构数据
          // this.optionsdata = this.jgListdata.map((item) => ({
          //   ...item,
          //   flag: true,
          // }));
          // this.anatomicStructurefn();

          // 获取图像大小并绘制
          this.getimgsize();
          this.draw('初始化画布', 'left');
          this.draw('初始化画布', 'right');
        } catch (error) {
          console.error('Error in gettpxq:', error);
        } finally {
          this.mentdata = this.rightPointnewdata.filter(
            (item) => item.medicineAtlasImgId == this.dcomid
          );
          this.loding = false;
        }
      },
      handleResize() {
        if (this.$refs.box) {
          this.hbheight = this.$refs.box.offsetHeight;
          this.hbwidth = this.$refs.box.offsetWidth;

          // 重新设置画布尺寸
          const canvas = document.getElementById('myCanvas');
          if (canvas) {
            canvas.width = this.hbwidth;
            canvas.height = this.hbheight;
          }

          // 重新设置覆盖层画布尺寸
          const overlayCanvas = document.getElementById('overlayCanvas');
          if (overlayCanvas) {
            overlayCanvas.width = this.hbwidth;
            overlayCanvas.height = this.hbheight;
          }

          // 重新加载图片并绘制
          const imgsrcd = this.imgsrc.find(
            (item) => item.medicineAtlasImgId === this.dcomid
          );
          if (imgsrcd) {
            // this.state.img.src = this.base + imgsrcd.imgUrl;
            this.state.img.src = require('@/assets/atlaimg/' +
              imgsrcd.imgUrl.replace(/^.*[\\/]/, ''));
            this.state.img.onload = () => {
              this.state.imgWidth = this.state.img.naturalWidth;
              this.state.imgHeight = this.state.img.naturalHeight;
              this.draw('页面更新画布', 'left');
              this.draw('页面更新画布', 'right');
            };
          }
        }
      },
      handleKeyDown(event) {
        if (event.key === ' ') {
          this.state.isSpacePressed = true;
        }
      },
      handleKeyUp(event) {
        if (event.key === ' ') {
          this.state.isSpacePressed = false;
        }
      },
      handleTouchStart(event) {
        event.preventDefault();
        if (event.touches.length === 2) {
          this.startX = event.touches[0].clientX;
          this.startY = event.touches[0].clientY;
          this.isSwiping = true;
          this.startTime = Date.now();
        }
      },
      handleTouchMove(event) {
        if (!this.isSwiping) return;
        event.preventDefault();
        const currentX = event.touches[0].clientX;
        const currentY = event.touches[0].clientY;
        const deltaX = currentX - this.startX;
        const deltaY = currentY - this.startY;
        const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
        const timeElapsed = Date.now() - this.startTime;
        if (distance > this.threshold) {
          this.hasMoved = true;
          if (
            distance > this.fastSwipeDistance &&
            timeElapsed < this.fastSwipeThreshold
          ) {
            this.isFastSwipe = true;
          }
        }
      },
      handleTouchEnd(event) {
        if (!this.isSwiping) return;
        event.preventDefault();
        this.isSwiping = false;
        if (this.hasMoved) {
          if (this.isFastSwipe) {
            this.handleFastSwipe();
          } else {
            this.handleSlowSwipe();
          }
        }
        this.hasMoved = false;
        this.isFastSwipe = false;
      },
      handleFastSwipe() {
        // const currentIndex = this.findindex()
        if (this.startX > this.$refs.box.offsetWidth / 2) {
          this.tagdcoms('1');
        } else {
          this.tagdcoms('-1');
        }
      },
      handleSlowSwipe() {
        // const currentIndex = this.findindex()
        if (this.startX > this.$refs.box.offsetWidth / 2) {
          this.tagdcoms('1');
        } else {
          this.tagdcoms('-1');
        }
      },
      touchStartHandler(event) {
        if (event.touches.length === 2) {
          this.startX = event.touches[0].clientX;
          this.startY = event.touches[0].clientY;
          this.isSwiping = true;
          this.startTime = Date.now();
        }
      },
      touchMoveHandler(event) {
        if (!this.isSwiping) return;
        const currentX = event.touches[0].clientX;
        const currentY = event.touches[0].clientY;
        const deltaX = currentX - this.startX;
        const deltaY = currentY - this.startY;
        const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
        const timeElapsed = Date.now() - this.startTime;
        if (distance > this.threshold) {
          this.hasMoved = true;
          if (
            distance > this.fastSwipeDistance &&
            timeElapsed < this.fastSwipeThreshold
          ) {
            this.isFastSwipe = true;
          }
        }
      },
      touchEndHandler() {
        console.log('event');

        if (!this.isSwiping) return;
        this.isSwiping = false;
        if (this.hasMoved) {
          if (this.isFastSwipe) {
            this.handleFastSwipe();
          } else {
            this.handleSlowSwipe();
          }
        }
        this.hasMoved = false;
        this.isFastSwipe = false;
      },
      startDrag(e) {
        if (!this.tdflag) {
          return;
        }
        console.log('当前拖动标记');
        // 判断是否为触摸事件
        const isTouchEvent = 'touches' in e;

        let clientX, clientY;

        if (isTouchEvent) {
          // 触摸事件
          clientX = e.touches[0].clientX;
          clientY = e.touches[0].clientY;
          e.preventDefault(); // 仅在触摸事件时调用 preventDefault
        } else {
          // 鼠标事件
          clientX = e.clientX;
          clientY = e.clientY;
          if (e.button === 0) {
            e.preventDefault(); // 仅在左键点击时调用 preventDefault
          }
        }

        // 判断是否为左键点击或触摸
        if ((e instanceof MouseEvent && e.button === 0) || isTouchEvent) {
          if (this.tdflag) {
            this.state.isDragging = true;

            // 获取 canvas 的位置和尺寸
            const rect = this.state.canvas.getBoundingClientRect();
            console.log('Canvas rect:', rect); // 输出 rect 检查是否精确

            // 确保在计算开始位置时能处理动态变化
            this.state.startDragX = clientX - rect.left - this.state.imgOffsetX;
            this.state.startDragY = clientY - rect.top - this.state.imgOffsetY;
          }
        }
      },
      handleMouseMove(event) {
        // 判断是否为触摸事件
        const isTouchEvent = 'touches' in event;
        let canvasX, canvasY;

        if (isTouchEvent) {
          // 获取触摸事件的坐标
          const touch = event.touches[0];
          const rect = this.state.canvas.getBoundingClientRect();
          canvasX = touch.clientX - rect.left;
          canvasY = touch.clientY - rect.top;
        } else {
          // 获取鼠标事件的坐标
          canvasX = event.offsetX;
          canvasY = event.offsetY;
        }

        if (this.state.isDragging) {
          this.dragMove(event);
        } else {
          this.checkHover(canvasX, canvasY, event);
          if (this.state.hoveredMarker) {
            // 判断鼠标当前所在的画布
            if (event.target && event.target.id === 'myCanvas') {
              // 鼠标在左侧画布
              // 可以在这里处理左侧画布的悬停逻辑
              this.draw('搜索', 'left');
            } else if (event.target && event.target.id === 'myCanvas2') {
              // 鼠标在右侧画布
              // 可以在这里处理右侧画布的悬停逻辑
              this.draw('搜索', 'right');
            }
          } else {
            this.draw('');
          }
        }
      },
      stopDrag() {
        this.state.isDragging = false;
        this.tdflag = false;
      },
      handleWheel(event) {
        event.preventDefault();
        const delta = event.deltaY > 0 ? 1 : -1;
        this.tagdcoms(delta.toString());
      },
      handleCanvasClick(event) {
        let canvasX, canvasY;

        if ('touches' in event) {
          // 触摸事件
          const touch = event.touches[0];
          const rect = this.state.canvas.getBoundingClientRect();
          canvasX = touch.clientX - rect.left;
          canvasY = touch.clientY - rect.top;
          this.checkHover(canvasX, canvasY, event);
          event.preventDefault();
        } else {
          // 鼠标事件
          canvasX = event.offsetX;
          canvasY = event.offsetY;
        }

        if (this.state.canBiaoZhu) {
          // 计算图像坐标
          // const imgX =
          //   (canvasX -
          //     (this.state.canvas.width / 2 -
          //       (this.state.imgWidth * this.state.imgScale) / 2)) /
          //   this.state.imgScale
          // const imgY =
          //   (canvasY -
          //     (this.state.canvas.height / 2 -
          //       (this.state.imgHeight * this.state.imgScale) / 2)) /
          //   this.state.imgScale
          // this.createMarker(imgX, imgY)
        } else if (this.state.hoveredMarker) {
          this.state.currentMarker = this.state.hoveredMarker;
          this.state.currentText = this.state.hoveredMarker.text || '';
          this.markingPointsId = this.state.hoveredMarker.markingPointsId;
          this.hoveredMarkerID = this.state.hoveredMarker.markingPointsId;
          this.draw('选中切换模式', 'right');
          this.draw('选中切换模式', 'left');
          console.log('有没有左右', this.markingPointsId);

          // this.draw(this.state.hoveredMarker);

          // getxqPoint({ markPointsId: this.markingPointsId }).then((res) => {
          //   if (res.code === 200) {
          //     this.visible = false
          //     this.bwstuddata = res.data
          //     // 再次查询点位知识点 中英文对照
          //     getPointjs({ pointName: res.data.pointName }).then((resd) => {
          //       this.bwstuddata.pointNameEng = resd.data.pointNameEng || ''
          //       this.bwstuddata.pointContent = resd.data.pointContent
          //       this.handleClick()
          //     })
          //   }
          // })
        }
      },
      checkHover(x, y, event) {
        // console.log('一定能够');

        this.state.hoveredMarker = null;
        this.myStyle = 'inherit';
        // 判断鼠标当前所在的画布
        // 判断当前画布，选择对应的 markers
        let markers, pointSize, imgScale;
        if (event.target && event.target.id === 'myCanvas') {
          markers = this.state.markers;
          pointSize = this.state.pointSize;
          imgScale = this.state.imgScale;
        } else if (event.target && event.target.id === 'myCanvas2') {
          markers = this.state.markers2;
          pointSize = this.state.pointSize;
          imgScale = this.state.imgScale;
        }
        // 从状态中解构出相关的属性

        // 合并 bsdata
        const mergedBsdata = markers.filter((item) =>
          item.medicineAtlasImgId.includes(this.dcomid)
        );
        const targetElement = { bsdata: [] };
        targetElement.bsdata = mergedBsdata.flatMap((item) => item.bsdata);

        if (targetElement) {
          // 找到目标标记元素中的标记
          for (let marker of targetElement.bsdata) {
            // 获取画布和上下文
            const canvas = this.state.canvas;
            const ctx = this.state.ctx;

            // 计算缩放后的图像尺寸
            const scaledWidth = this.state.imgWidth * imgScale;
            const scaledHeight = this.state.imgHeight * imgScale;

            // 计算图像在画布上的偏移量
            const xOffset =
              (canvas.width - scaledWidth) / 2 + this.state.imgOffsetX;
            const yOffset =
              (canvas.height - scaledHeight) / 2 + this.state.imgOffsetY;

            // 计算标记的位置
            const markerX = marker.x * imgScale + xOffset;
            const markerY = marker.y * imgScale + yOffset;

            // 检查是否悬停在标记点上
            if (
              Math.hypot(x - markerX, y - markerY) <
              pointSize * imgScale * 3
            ) {
              this.state.hoveredMarker = marker;
              this.myStyle = 'pointer';
              return true;
            }

            // 检查是否悬停在文本上
            const text = marker.text || '';
            ctx.font = '12px Arial'; // 根据实际使用的字体进行设置
            const textMetrics = ctx.measureText(text);
            const textWidth = textMetrics.width;

            const textX = marker.textX;
            const textY = marker.textY;
            const textHeight = 14 * imgScale;

            // 计算文本的边界框
            const textBoundingBox = {
              left: textX - textWidth - 100,
              right: textX + textWidth + 100,
              top: textY - textHeight,
              bottom: textY,
            };

            if (
              x >= textBoundingBox.left &&
              x <= textBoundingBox.right &&
              y >= textBoundingBox.top &&
              y <= textBoundingBox.bottom
            ) {
              this.myStyle = 'pointer';
              this.state.hoveredMarker = marker;
              return true;
            }
          }
        }

        // 没有悬停在任何标记、线段或文本上
        this.state.hoveredMarker = null;
        return false;
      },
      dragMove(e) {
        // 判断是否是鼠标事件还是触摸事件
        const clientX =
          e instanceof MouseEvent ? e.clientX : e.touches[0].clientX;
        const clientY =
          e instanceof MouseEvent ? e.clientY : e.touches[0].clientY;

        if (this.state.isDragging) {
          const rect = this.state.canvas.getBoundingClientRect();
          this.state.imgOffsetX = clientX - rect.left - this.state.startDragX;
          this.state.imgOffsetY = clientY - rect.top - this.state.startDragY;
          this.draw('拖拽更新画布', 'left');
          this.draw('拖拽更新画布', 'right');
        }
      },
      // 可删除此版本用不到
      // createMarker(x, y) {
      //   // 创建新标记的逻辑
      //   const newMarker = {
      //     x,
      //     y,
      //     text: '',
      //     color: this.state.pointColor,
      //     flag: true,
      //     labels: true
      //   }

      //   // 添加到当前图片的标记中
      //   const currentImageMarkers = this.state.markers.find(
      //     (marker) => marker.medicineAtlasImgId === this.dcomid
      //   )

      //   if (currentImageMarkers) {
      //     currentImageMarkers.bsdata.push(newMarker)
      //   } else {
      //     this.state.markers.push({
      //       medicineAtlasImgId: this.dcomid,
      //       bsdata: [newMarker]
      //     })
      //   }

      //   this.saveMarkers()
      //   this.draw('')
      // },
      // handleClick() {
      //   this.visible = true;
      // },
      loadMarkers() {
        // const savedMarkers = localStorage.getItem('markers');
        // if (savedMarkers) {
        //   this.state.markers = JSON.parse(savedMarkers);
        // }
      },
      saveMarkers() {
        // localStorage.setItem('markers', JSON.stringify(this.state.markers));
      },
      draw(type, targetCanvas) {
        // console.log('当前来源', type, targetCanvas);

        // console.log(
        //   '当前绘制',
        //   targetCanvas,
        //   targetCanvas == 'left' ? this.state.markers : this.state.markers2,
        //   '来自',
        //   type
        // );

        if (!this.state.ctx || !this.state.img || !this.state.canvas) {
          console.warn('Canvas or image not ready');
          return;
        }
        if (this.state.imgWidth == 0) {
          console.warn('Image width is 0');
          return;
        }
        // 特殊处理

        console.log('渲染时候宽高', this.state.img.naturalWidth);

        // 选择目标画布和上下文
        const canvas =
          targetCanvas === 'left' ? this.state.canvas : this.state.canvas2;
        const ctx = targetCanvas === 'left' ? this.state.ctx : this.state.ctx2;
        const img =
          targetCanvas === 'left' ? this.state.img : this.state.rightimg;

        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // let scaledWidth = this.state.img.naturalWidth * this.state.imgScale;
        // let scaledHeight = this.state.img.naturalHeight * this.state.imgScale;
        // let scaledWidth = 820 * this.state.imgScale;
        // let scaledHeight = 560 * this.state.imgScale;
        let scaledWidth = null;
        let scaledHeight = null;
        // // // 特殊处理格式
        if (targetCanvas != 'left') {
          this.state.imgScale = 2;
          scaledWidth = 410 * this.state.imgScale;
          scaledHeight = 280 * this.state.imgScale;
        } else {
          this.state.imgScale = 1;
          scaledWidth = 820 * this.state.imgScale;
          scaledHeight = 560 * this.state.imgScale;
        }
        // 计算图像在画布上的偏移
        const xOffset =
          (canvas.width - scaledWidth) / 2 + this.state.imgOffsetX;
        const yOffset =
          (canvas.height - scaledHeight) / 2 + this.state.imgOffsetY;

        ctx.save();

        // 应用变换
        ctx.translate(canvas.width / 2, canvas.height / 2);
        if (this.state.flipHorizontal) ctx.scale(-1, 1);
        if (this.state.flipVertical) ctx.scale(1, -1);
        ctx.rotate((this.state.rotation * Math.PI) / 180);
        ctx.translate(-canvas.width / 2, -canvas.height / 2);

        // 绘制图像
        ctx.drawImage(img, xOffset, yOffset, scaledWidth, scaledHeight);

        // 恢复上下文状态为绘制标记做准备
        ctx.restore();
        ctx.save();

        // 重新应用变换
        ctx.translate(canvas.width / 2, canvas.height / 2);
        if (this.state.flipHorizontal) ctx.scale(-1, 1);
        if (this.state.flipVertical) ctx.scale(1, -1);
        ctx.rotate((this.state.rotation * Math.PI) / 180);
        ctx.translate(-canvas.width / 2, -canvas.height / 2);

        const margin = 200; // 从画布边缘的边距
        let textHeight = 16; // 文本高度
        let verticalSpacing = 5; // 文本之间的垂直间隔
        const textMargin = 20; // 文本与边缘的距离
        ctx.font = '15px Arial';
        // 记录所有标记的位置和文本
        this.leftMarkers = [];
        this.rightMarkers = [];

        // 定义绘制标记和文本的函数
        const drawMarkersAndText = (markers, isLeft, targetCanvas) => {
          markers.forEach((item) => {
            if (!item.medicineAtlasImgId) return;
            const itemsArray = item.medicineAtlasImgId.split(',').map(Number);

            if (itemsArray.includes(this.dcomid)) {
              item.bsdata.forEach((marker) => {
                const markerX = marker.x * this.state.imgScale + xOffset;
                const markerY = marker.y * this.state.imgScale + yOffset;

                // 绘制标记点
                if (marker.flag) {
                  if (marker.tack) {
                    // 开启大头针
                    ctx.beginPath();

                    // 定义大头针参数
                    const baseSize = this.state.pointSize;
                    const radius = baseSize * 1.5;
                    const height = baseSize * 3;

                    // 绘制顶部圆形
                    ctx.arc(markerX, markerY, radius, Math.PI, 0, false);

                    // 绘制底部尖角
                    ctx.lineTo(markerX, markerY + height);
                    ctx.lineTo(markerX - radius, markerY);

                    // 完成路径
                    ctx.closePath();

                    // 设置样式并填充
                    ctx.fillStyle =
                      marker == this.state.hoveredMarker
                        ? '#409EFF'
                        : '#' + marker.color;
                    ctx.fill();

                    // 如果需要边框
                    ctx.lineWidth = 2;
                    ctx.strokeStyle = 'black';
                    ctx.stroke();
                  } else {
                    // 未开启大头针

                    if (type == '选中切换模式') {
                      // console.log(
                      //   '执行了',
                      //   marker.markingPointsId ==
                      //     this.state.hoveredMarker.markingPointsId
                      // );
                      ctx.fillStyle =
                        marker.text == this.state.hoveredMarker.text
                          ? 'rgba(255, 0, 0, 1)'
                          : 'rgba(128, 128, 128, 0.5)';
                      // ctx.fillStyle =
                      //   marker.markingPointsId ==
                      //   this.state.hoveredMarker.markingPointsId
                      //     ? 'rgba(255, 0, 0, 1)'
                      //     : 'rgba(128, 128, 128, 0.5)';
                    } else if (type == '搜索') {
                      // console.log('marker', marker);
                      ctx.fillStyle =
                        marker.text == this.state.hoveredMarker.text
                          ? 'rgba(255, 0, 0, 1)'
                          : 'rgba(128, 128, 128, 0.5)';
                      // ctx.fillStyle =
                      //   marker == this.state.hoveredMarker
                      //     ? 'rgba(255, 0, 0, 1)'
                      //     : 'rgba(128, 128, 128, 0.5)';
                    } else {
                      // 默认模式
                      ctx.fillStyle =
                        marker == this.state.hoveredMarker
                          ? '#409EFF'
                          : '#' + marker.color;
                    }
                    ctx.beginPath();
                    // ctx.fillText(marker.text, markerX, markerY);
                    ctx.fillText(marker.index, markerX, markerY);
                    // ctx.arc(
                    //   markerX,
                    //   markerY,
                    //   this.state.pointSize / 2,
                    //   0,
                    //   2 * Math.PI
                    // );
                    // ctx.arc(
                    //   markerX,
                    //   markerY,
                    //   this.state.pointSize / 2,
                    //   0,
                    //   2 * Math.PI
                    // );
                    ctx.fill();
                  }
                }
              });
            }
          });
        };

        // 先区别是左右哪一个画布，然后再在其中一个画布上绘制左侧和右侧的标记

        drawMarkersAndText(
          targetCanvas == 'left' ? this.state.markers : this.state.markers2,
          true,
          targetCanvas
        );
        drawMarkersAndText(
          targetCanvas == 'left' ? this.state.markers : this.state.markers2,
          false,
          targetCanvas
        );

        // 左右数组优化调整顺序
        // this.leftMarkers.sort((a, b) => a.y - b.y);
        // this.rightMarkers.sort((a, b) => a.y - b.y);

        // 恢复上下文状态
        ctx.restore();
        this.loding = false;
      },
      zoomIn() {
        this.selectedTool = 'zoom';
        this.state.imgScale = Math.min(
          3,
          this.state.imgScale + this.state.zoomStep
        );
        this.draw('缩小更新画布', 'left');
        this.draw('缩小更新画布', 'right');
      },
      zoomOut() {
        this.selectedTool = 'zoom';
        this.state.imgScale = Math.max(
          0.1,
          this.state.imgScale - this.state.zoomStep
        );
        this.draw('放大更新画布', 'left');
        this.draw('放大更新画布', 'right');
      },
      reset() {
        this.selectedTool = 'reset';
        this.getimgsize();

        this.state.imgOffsetX = 0;
        this.state.imgOffsetY = 0;
        this.state.rotation = 0;
        this.state.flipHorizontal = false;
        this.state.flipVertical = false;
        this.draw('重置更新画布', 'left');
        this.draw('重置更新画布', 'right');
        // 清空标记点
        this.clearOverlay();
      },
      toggleLinesAndText() {
        this.state.showLinesAndText = !this.state.showLinesAndText;
        this.draw('切换显示线段', 'left');
        this.draw('切换显示线段', 'right');
      },
      flipHorizontald() {
        this.state.flipHorizontal = !this.state.flipHorizontal;
        this.draw('水平旋转', 'left');
        this.draw('水平旋转', 'right');
      },
      flipVerticald() {
        this.state.flipVertical = !this.state.flipVertical;
        this.draw('垂直旋转', 'left');
        this.draw('垂直旋转', 'right');
      },
      rotate90() {
        this.state.rotation = (this.state.rotation + 90) % 360;
        this.draw('旋转更新画布', 'left');
        this.draw('旋转更新画布', 'right');
      },
      rotateMinus90() {
        this.state.rotation = (this.state.rotation - 90) % 360;
        this.draw('旋转更新画布2', 'left');
        this.draw('旋转更新画布2', 'right');
      },
      anatomicStructurefn() {
        this.anatomicStructure = [];
        this.optionsdata.forEach((items) => {
          this.state.markers.some((item) => {
            if (!item.medicineAtlasImgId) {
              return;
            }

            const itemsArray = item.medicineAtlasImgId.split(',').map(Number);
            if (itemsArray.includes(this.dcomid)) {
              item.bsdata.forEach((itemd) => {
                if (itemd.anatomicStructureId == items.anatomicStructureId) {
                  // 先检查是否已存在
                  const exists = this.anatomicStructure.some(
                    (a) => a.anatomicStructureId === items.anatomicStructureId
                  );

                  if (!exists) {
                    this.anatomicStructure.push(items);
                  }
                }
              });
            }
            return false;
          });
        });
        // console.log(
        //   '处理完成的数据',
        //   this.anatomicStructure,
        //   this.optionsdata,
        //   this.state.markers
        // );
      },
      flagfn(item) {
        return this.state.markers.some((marker) => {
          const itemsArray = marker.medicineAtlasImgId.split(',').map(Number);
          if (itemsArray.includes(this.dcomid)) {
            return marker.bsdata.some(
              (itemd) => itemd.anatomicStructureId === item.anatomicStructureId
            );
          }
          return false;
        });
      },
      changecs(item) {
        console.log('关联解剖结构测试', this.anatomicStructure, item);
        this.state.markers.some((marker) => {
          marker.bsdata.some((itemd) => {
            if (itemd.anatomicStructureId == item.anatomicStructureId) {
              itemd.flag = item.flag;
            }
          });
        });

        // 判断是否存在 flag 为 false 的项
        this.allflag = !this.anatomicStructure.some(
          (item) => item.flag === false
        );

        this.draw('切换解刨');
      },
      changeimgclassfn(name) {
        this.classificationName = name;
        this.imgsrc = [];
        this.imgsrcs.forEach((item) => {
          if (this.classificationName === item.imgClassificationName) {
            this.imgsrc.push(item);
          }
        });

        if (name === '全部') {
          this.imggroupname = '全部';
          this.imgsrc = this.imgsrcs;
          this.dcomid = this.imgsrc[0].medicineAtlasImgId;
          this.tagdcom(this.dcomid, '');
          return;
        }

        if (this.imggroupname !== '全部') {
          this.changeimggroupfn(this.imggroupname, false);
        }

        this.dcomid = this.imgsrc[0].medicineAtlasImgId;
        this.tagdcom(this.dcomid, '');
      },
      changeimggroupfn(name, flag) {
        if (name === '全部' && flag) {
          this.imggroupname = '全部';
          this.changeimgclassfn(this.classificationName);
          return;
        }

        this.imggroupname = name;
        const item = this.imggroup.find(
          (img) => img.typeName === this.imggroupname
        );

        const imgsrcsd = item;
        const imgsrcmw = this.imgsrc;
        this.imgsrc = [];

        // 判断解剖面是默认或者全选状态的时候默认选择第一个选项
        if (this.classificationName === '全部') {
          this.classificationName = this.imgclassdata[0].classificationName;
        }

        // 判断完成
        if (this.classificationName !== '') {
          imgsrcsd.typeImg.forEach((itemd) => {
            if (
              this.classificationName === itemd.imgClassificationName &&
              this.imggroupname === itemd.typeName
            ) {
              this.imgsrc.push(itemd);
            }
          });
        } else {
          this.imgsrc = imgsrcsd.typeImg;
        }

        if (this.imgsrc.length > 0) {
          this.dcomid = this.imgsrc[0].medicineAtlasImgId;
          this.tagdcom(this.dcomid, '');
        } else {
          console.log('当前图像没有T2', this.imgsrc);
          this.imgsrc = imgsrcmw;

          this.$message.warning('暂无图像，请更换其他解剖面后再选择加权！');
          this.imggroupname = '全部';
        }
      },
      findindex() {
        return this.imgsrc.findIndex(
          (item) => item.medicineAtlasImgId === this.dcomid
        );
      },
      // 封装
      getimgsize() {
        const canvas = this.state.canvas;
        const aspectRatio =
          this.state.img.naturalWidth / this.state.img.naturalHeight;
        const canvasAspectRatio = canvas.width / canvas.height;
        // 设置最大宽度和高度
        const maxWidth = canvas.width * 0.99; // 画布宽度的99.9%
        const maxHeight = canvas.height * 0.99; // 画布高度的99.9%

        if (canvasAspectRatio > aspectRatio) {
          this.state.imgScale = Math.min(
            maxHeight / this.state.img.naturalHeight,
            1
          );
        } else {
          this.state.imgScale = Math.min(
            maxWidth / this.state.img.naturalWidth,
            1
          );
        }
      },
      async tagdcom(id, type) {
        // console.log('当前图片id', id);

        // 处理一下当前 最新菜单
        // 提取 rightPointnewdata 中 medicineAtlasImgId 等于 id 的项到 mentdata
        this.mentdata = this.rightPointnewdata.filter(
          (item) => item.medicineAtlasImgId == id
        );
        // 处理完成
        this.getimgsize();
        if (id) {
          this.dcomid = id;
          localStorage.setItem('dcomid', id);
        }
        // 左侧渲染
        const imgsrcd = this.imgsrc.find(
          (item) => item.medicineAtlasImgId === this.dcomid
        );
        // 右侧渲染
        const rightimgsrcd = this.rightimgsrc.find(
          (item) => item.medicineAtlasImgId === this.dcomid
        );
        // 用 Promise 包裹图片加载
        const leftPromise = imgsrcd
          ? new Promise((resolve) => {
              this.state.img.src = require('@/assets/atlaimg/' +
                imgsrcd.imgUrl.replace(/^.*[\\/]/, ''));

              // this.state.img.src = this.base + imgsrcd.imgUrl;
              this.state.img.onload = () => {
                this.state.imgWidth = this.state.img.naturalWidth;
                this.state.imgHeight = this.state.img.naturalHeight;
                if (type == '搜索') {
                  this.draw('搜索', 'left');
                } else {
                  this.draw('切换图谱', 'left');
                }
                resolve();
              };
            })
          : Promise.resolve();

        const rightPromise = rightimgsrcd
          ? new Promise((resolve) => {
              // this.state.rightimg.src = this.base + rightimgsrcd.imgUrl;

              this.state.rightimg.src = require('@/assets/atlaimg/' +
                rightimgsrcd.imgUrl.replace(/^.*[\\/]/, ''));

              this.state.rightimg.onload = () => {
                this.state.imgWidth = this.state.rightimg.naturalWidth;
                this.state.imgHeight = this.state.rightimg.naturalHeight;
                // console.log('获取右侧的宽高', this.state.rightimg.naturalWidth);

                if (type == '搜索') {
                  this.draw('搜索', 'right');
                } else {
                  this.draw('切换图谱', 'right');
                }
                resolve();
              };
            })
          : Promise.resolve();

        // 等待左右图片都加载并绘制完
        await Promise.all([leftPromise, rightPromise]);
      },
      tagdcoms(type) {
        this.hoveredMarkerID = 0;
        const currentIndex = this.findindex();
        let newIndex = currentIndex;

        if (type === '1') {
          // 如果已经是最后一个，则禁止往后
          if (currentIndex >= this.imgsrc.length - 1) return;
          newIndex = currentIndex + 1;
        } else {
          // 如果已经是第一个，则禁止往前
          if (currentIndex <= 0) return;
          newIndex = currentIndex - 1;
        }

        this.tagdcom(this.imgsrc[newIndex].medicineAtlasImgId, '');
      },
      getScrollPosition(event) {
        const scrollLeft = event.target.scrollLeft;
        const scrollWidth = event.target.scrollWidth;
        const clientWidth = event.target.clientWidth;
        if (scrollLeft + clientWidth >= scrollWidth) {
          this.tagdcoms('1');
        } else if (scrollLeft === 0) {
          this.tagdcoms('-1');
        }
      },
      goback() {
        window.close();
        // this.$router.go(-1)
      },

      toggleTextButton() {
        this.draw('');
      },
      pzfn() {
        this.isCanvasVisible = this.pzshow;
        if (this.pzshow) {
          this.currentMode = 'drawing';
          this.currentCursorStyle = 'crosshair';

          this.$nextTick(() => {
            // const myCanvas = document.getElementById('myCanvas');
            const overlayCanvas = document.getElementById('overlayCanvas');

            // 获取画布上下文
            // this.context = myCanvas.getContext('2d', {
            //   willReadFrequently: true,
            // });
            this.overlayContext = overlayCanvas.getContext('2d', {
              willReadFrequently: true,
            });

            // 保存初始状态
            this.canvasHistory.push(
              this.overlayContext.getImageData(
                0,
                0,
                overlayCanvas.width,
                overlayCanvas.height
              )
            );
          });
        } else {
          this.currentMode = null;
          this.currentCursorStyle = 'inherit';
          // 清除画布内容
          const overlayCanvas = this.$refs.overlayCanvas;
          if (overlayCanvas) {
            const ctx = overlayCanvas.getContext('2d');
            ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
          }
        }
      },
      jubu() {
        const matchingItems = this.state.markers.filter((item) =>
          item.medicineAtlasImgId.includes(this.dcomid)
        );

        matchingItems.forEach((item) => {
          item.bsdata.forEach((items) => {
            items.labels = !this.jubushow; // 切换标签状态
          });
        });

        this.saveMarkers();
        this.draw('');

        const canvasContainer = document.getElementById('canvasContainer');
        if (!canvasContainer) return; // 确保容器存在

        // 确保父容器是相对定位
        canvasContainer.style.position = 'relative';

        // 检查是否已有子画布，若存在则移除并退出
        const existingOverlayCanvas = canvasContainer.querySelector(
          'canvas[data-role="overlay"]'
        );
        if (existingOverlayCanvas) {
          canvasContainer.removeChild(existingOverlayCanvas);
          canvasContainer
            .querySelectorAll('div[data-role="resize-handle"]')
            .forEach((circle) => circle.remove());
          return; // 不再执行后续代码
        }

        // 创建并设置新的子 canvas
        const overlayCanvas = document.createElement('canvas');
        overlayCanvas.width = 80;
        overlayCanvas.height = 80;
        overlayCanvas.style.cssText = `
            border: 1px solid ${
              this.atlasTypeName == '插画' ? 'red' : '#ffffff'
            };
            position: absolute;
            z-index: 10;
            left: 750px; /* 初始位置 */
            top: 350px; /* 初始位置 */
            cursor: move;
          `;
        overlayCanvas.setAttribute('data-role', 'overlay'); // 添加标识以便后续查找
        canvasContainer.appendChild(overlayCanvas);

        // 当前画布状态
        let currentState = {
          width: overlayCanvas.width,
          height: overlayCanvas.height,
          left: parseFloat(overlayCanvas.style.left),
          top: parseFloat(overlayCanvas.style.top),
        };

        // 是否在拖动模式
        let isDragging = false;
        let dragOffsetX = 0;
        let dragOffsetY = 0;

        // 判断是否为触摸设备
        const isTouchDevice =
          'ontouchstart' in window &&
          window.matchMedia('(pointer: coarse)').matches;

        // 画布拖动逻辑
        const startDragx = (e) => {
          e.preventDefault();
          isDragging = true;
          const clientX = isTouchDevice ? e.touches[0].clientX : e.clientX;
          const clientY = isTouchDevice ? e.touches[0].clientY : e.clientY;
          dragOffsetX = clientX - overlayCanvas.offsetLeft;
          dragOffsetY = clientY - overlayCanvas.offsetTop;

          const onMove = (moveEvent) => {
            if (!isDragging) return;
            const newX =
              (isTouchDevice
                ? moveEvent.touches[0].clientX
                : moveEvent.clientX) - dragOffsetX;
            const newY =
              (isTouchDevice
                ? moveEvent.touches[0].clientY
                : moveEvent.clientY) - dragOffsetY;
            currentState.left = newX;
            currentState.top = newY;

            overlayCanvas.style.left = `${newX}px`;
            overlayCanvas.style.top = `${newY}px`;

            updateControlPoints();
            updateMarkers(); // 更新标记点状态
          };

          const stopDragx = () => {
            isDragging = false;
            window.removeEventListener(
              isTouchDevice ? 'touchmove' : 'mousemove',
              onMove
            );
            window.removeEventListener(
              isTouchDevice ? 'touchend' : 'mouseup',
              stopDragx
            );
            this.draw(''); // 拖动完成后更新画布
          };

          window.addEventListener(
            isTouchDevice ? 'touchmove' : 'mousemove',
            onMove
          );
          window.addEventListener(
            isTouchDevice ? 'touchend' : 'mouseup',
            stopDragx
          );
        };

        overlayCanvas.addEventListener(
          isTouchDevice ? 'touchstart' : 'mousedown',
          startDragx
        );

        // 更新圆点位置
        const updateControlPoints = () => {
          const canvasRect = overlayCanvas.getBoundingClientRect();
          const containerRect = canvasContainer.getBoundingClientRect();

          const controlPoints = [
            {
              x: canvasRect.left - containerRect.left,
              y: canvasRect.top - containerRect.top,
            }, // 左上角
            {
              x: canvasRect.left - containerRect.left + canvasRect.width / 2,
              y: canvasRect.top - containerRect.top,
            }, // 顶边中心
            {
              x: canvasRect.right - containerRect.left,
              y: canvasRect.top - containerRect.top,
            }, // 右上角
            {
              x: canvasRect.left - containerRect.left,
              y: canvasRect.top - containerRect.top + canvasRect.height / 2,
            }, // 左边中心
            {
              x: canvasRect.right - containerRect.left,
              y: canvasRect.top - containerRect.top + canvasRect.height / 2,
            }, // 右边中心
            {
              x: canvasRect.left - containerRect.left,
              y: canvasRect.bottom - containerRect.top,
            }, // 左下角
            {
              x: canvasRect.left - containerRect.left + canvasRect.width / 2,
              y: canvasRect.bottom - containerRect.top,
            }, // 底边中心
            {
              x: canvasRect.right - containerRect.left,
              y: canvasRect.bottom - containerRect.top,
            }, // 右下角
          ];

          controlHandles.forEach((circle, index) => {
            circle.style.left = `${controlPoints[index].x - 5}px`;
            circle.style.top = `${controlPoints[index].y - 5}px`;
          });
        };

        // 更新标记点状态
        const updateMarkers = () => {
          const scaledWidth = this.state.img.naturalWidth * this.state.imgScale;
          const scaledHeight =
            this.state.img.naturalHeight * this.state.imgScale;

          const canvasOffsetX =
            (this.state.canvas.width - scaledWidth) / 2 + this.state.imgOffsetX;
          const canvasOffsetY =
            (this.state.canvas.height - scaledHeight) / 2 +
            this.state.imgOffsetY;

          const localCanvasLeft = currentState.left - canvasOffsetX;
          const localCanvasTop = currentState.top - canvasOffsetY;
          const localCanvasRight = localCanvasLeft + currentState.width;
          const localCanvasBottom = localCanvasTop + currentState.height;

          matchingItems.forEach((item) => {
            item.bsdata.forEach((marker) => {
              const scaledMarkerX = marker.x * this.state.imgScale;
              const scaledMarkerY = marker.y * this.state.imgScale;

              const isInside =
                scaledMarkerX >= localCanvasLeft &&
                scaledMarkerX <= localCanvasRight &&
                scaledMarkerY >= localCanvasTop &&
                scaledMarkerY <= localCanvasBottom;

              marker.labels = isInside; // 根据是否在区域内更新状态
            });
          });
        };

        // 添加圆点
        const controlHandles = [];
        const createCircle = (index) => {
          const circle = document.createElement('div');
          circle.style.cssText = `
              width: 10px;
              height: 10px;
              background-color: #ff0000;
              border-radius: 50%;
              position: absolute;
              z-index: 15;
              cursor: pointer;
            `;
          circle.setAttribute('data-index', index);
          circle.setAttribute('data-role', 'resize-handle');
          canvasContainer.appendChild(circle);
          return circle;
        };

        for (let i = 0; i < 8; i++) {
          const circle = createCircle(i);
          controlHandles.push(circle);
          let isResizing = false;

          circle.addEventListener(
            isTouchDevice ? 'touchstart' : 'mousedown',
            (e) => {
              e.preventDefault();
              e.stopPropagation(); // 防止触发拖动事件
              isResizing = true;

              const startX = isTouchDevice ? e.touches[0].clientX : e.clientX;
              const startY = isTouchDevice ? e.touches[0].clientY : e.clientY;

              const startState = { ...currentState };

              const onResizeMove = (moveEvent) => {
                if (!isResizing) return;

                const dx =
                  (isTouchDevice
                    ? moveEvent.touches[0].clientX
                    : moveEvent.clientX) - startX;
                const dy =
                  (isTouchDevice
                    ? moveEvent.touches[0].clientY
                    : moveEvent.clientY) - startY;

                switch (i) {
                  case 0: // 左上角
                    currentState.width = startState.width - dx;
                    currentState.height = startState.height - dy;
                    currentState.left = startState.left + dx;
                    currentState.top = startState.top + dy;
                    break;
                  case 1: // 顶边中心
                    currentState.height = startState.height - dy;
                    currentState.top = startState.top + dy;
                    break;
                  case 2: // 右上角
                    currentState.width = startState.width + dx;
                    currentState.height = startState.height - dy;
                    currentState.top = startState.top + dy;
                    break;
                  case 3: // 左边中心
                    currentState.width = startState.width - dx;
                    currentState.left = startState.left + dx;
                    break;
                  case 4: // 右边中心
                    currentState.width = startState.width + dx;
                    break;
                  case 5: // 左下角
                    currentState.width = startState.width - dx;
                    currentState.height = startState.height + dy;
                    currentState.left = startState.left + dx;
                    break;
                  case 6: // 底边中心
                    currentState.height = startState.height + dy;
                    break;
                  case 7: // 右下角
                    currentState.width = startState.width + dx;
                    currentState.height = startState.height + dy;
                    break;
                }

                overlayCanvas.style.width = `${currentState.width}px`;
                overlayCanvas.style.height = `${currentState.height}px`;
                overlayCanvas.style.left = `${currentState.left}px`;
                overlayCanvas.style.top = `${currentState.top}px`;

                updateControlPoints();
                updateMarkers();
              };

              const stopResize = () => {
                isResizing = false;
                window.removeEventListener(
                  isTouchDevice ? 'touchmove' : 'mousemove',
                  onResizeMove
                );
                window.removeEventListener(
                  isTouchDevice ? 'touchend' : 'mouseup',
                  stopResize
                );
                this.draw(''); // 调整完成后更新画布
              };

              window.addEventListener(
                isTouchDevice ? 'touchmove' : 'mousemove',
                onResizeMove
              );
              window.addEventListener(
                isTouchDevice ? 'touchend' : 'mouseup',
                stopResize
              );
            }
          );
        }

        updateControlPoints(); // 初始化控制点位置
        updateMarkers(); // 初始化标记点状态
      },
      handleCancelst() {
        this.visiblest = false;
      },

      enableDrawingMode() {
        this.pzshow = true;
        this.pzfn();
        this.currentMode = 'drawing';
        this.currentCursorStyle = 'crosshair';
        this.selectedTool = 'drawing';
        this.isEraserMode = false; // 确保橡皮擦模式关闭
        this.brushColor = '#ff0000'; // 重置画笔颜色为红色
      },
      enableTextMode() {
        this.pzshow = true;
        this.pzfn();
        this.currentMode = 'text';
        this.currentCursorStyle = 'text';
        this.selectedTool = 'text';
      },
      toggleEraser() {
        this.isEraserMode = !this.isEraserMode;
        this.brushColor = this.isEraserMode ? '#ffffff' : '#ff0000';
        this.selectedTool = this.isEraserMode ? 'eraser' : null;
        this.currentCursorStyle = this.isEraserMode
          ? "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'><path fill='%23ffffff' d='M15.14,3C14.63,3 14.12,3.2 13.73,3.59L2.59,14.73C1.81,15.5 1.81,16.77 2.59,17.54L5.03,20H12.69L21.41,11.27C22.19,10.5 22.19,9.23 21.41,8.46L16.86,3.59C16.46,3.2 15.95,3 15.14,3M17,7L19,9L15,13L13,11L17,7M3,21L5,19L7,21L9,19L11,21L13,19L15,21L17,19L19,21L21,19L19,17L21,15L19,13L21,11L19,9L21,7L19,5L21,3L19,5L17,3L15,5L13,3L11,5L9,3L7,5L5,3L7,5L5,7L3,9L5,11L3,13L5,15L3,17L5,19L3,21Z'/></svg>\") 12 12, auto"
          : 'crosshair';
      },
      enableRectangleMode() {
        this.pzshow = true;
        this.pzfn();
        this.currentMode = 'rectangle';
        this.currentCursorStyle = 'crosshair';
        this.selectedTool = 'rectangle';
        this.isEraserMode = false;
      },

      enableCircleMode() {
        this.pzshow = true;
        this.pzfn();
        this.currentMode = 'circle';
        this.currentCursorStyle = 'crosshair';
        this.selectedTool = 'circle';
        this.isEraserMode = false;
      },

      enableArrowMode() {
        this.pzshow = true;
        this.pzfn();
        this.currentMode = 'arrow';
        this.currentCursorStyle = 'crosshair';
        this.selectedTool = 'arrow';
        this.isEraserMode = false;
      },

      startDrawing(event) {
        if (
          !['drawing', 'rectangle', 'circle', 'arrow'].includes(
            this.currentMode
          )
        )
          return;
        console.log('执行了开始绘制', this.currentMode);

        this.isDrawing = true;
        const rect = document
          .getElementById('overlayCanvas')
          .getBoundingClientRect();

        // 获取起始点坐标
        if (event.touches && event.touches.length > 0) {
          this.startX = event.touches[0].clientX - rect.left;
          this.startY = event.touches[0].clientY - rect.top;
        } else {
          this.startX = event.clientX - rect.left;
          this.startY = event.clientY - rect.top;
        }

        // 如果是绘制模式，初始化路径
        if (this.currentMode === 'drawing') {
          this.overlayContext.beginPath();
          this.overlayContext.moveTo(this.startX, this.startY);
        }

        // 只在第一次开始绘制时保存初始状态
        if (this.canvasHistory.length === 0) {
          const canvas = document.getElementById('overlayCanvas');
          const currentState = this.overlayContext.getImageData(
            0,
            0,
            canvas.width,
            canvas.height
          );
          this.canvasHistory.push(currentState);
        }
      },

      draws(event) {
        event.preventDefault();
        if (!this.isDrawing || !this.overlayContext) return;

        const rect = document
          .getElementById('overlayCanvas')
          .getBoundingClientRect();
        let currentX, currentY;

        if (event.touches && event.touches.length > 0) {
          currentX = event.touches[0].clientX - rect.left;
          currentY = event.touches[0].clientY - rect.top;
        } else {
          currentX = event.clientX - rect.left;
          currentY = event.clientY - rect.top;
        }

        // 清除上一帧
        this.overlayContext.clearRect(0, 0, rect.width, rect.height);

        // 恢复上一帧
        if (this.canvasHistory.length > 0) {
          const lastState = this.canvasHistory[this.canvasHistory.length - 1];
          this.overlayContext.putImageData(lastState, 0, 0);
        }

        // 设置绘制样式
        this.overlayContext.strokeStyle = this.brushColor;
        this.overlayContext.lineWidth = this.brushSize;
        this.overlayContext.lineCap = 'round';
        this.overlayContext.lineJoin = 'round';

        if (this.currentMode === 'drawing') {
          if (this.isEraserMode) {
            // 如果是橡皮擦模式，擦除线段
            this.erase(currentX, currentY);
          } else {
            // 绘制模式 - 使用 lineTo 连接路径
            this.overlayContext.lineTo(currentX, currentY);
            this.overlayContext.stroke();
          }
        } else if (this.currentMode === 'rectangle') {
          const width = currentX - this.startX;
          const height = currentY - this.startY;
          this.overlayContext.strokeRect(
            this.startX,
            this.startY,
            width,
            height
          );
        } else if (this.currentMode === 'circle') {
          const radius = Math.sqrt(
            Math.pow(currentX - this.startX, 2) +
              Math.pow(currentY - this.startY, 2)
          );
          this.overlayContext.beginPath();
          this.overlayContext.arc(
            this.startX,
            this.startY,
            radius,
            0,
            2 * Math.PI
          );
          this.overlayContext.stroke();
        } else if (this.currentMode === 'arrow') {
          // 绘制箭头主体
          this.overlayContext.beginPath();
          this.overlayContext.moveTo(this.startX, this.startY);
          this.overlayContext.lineTo(currentX, currentY);
          this.overlayContext.stroke();

          // 计算箭头角度
          const angle = Math.atan2(
            currentY - this.startY,
            currentX - this.startX
          );
          const arrowLength = 20; // 箭头长度
          const arrowAngle = Math.PI / 6; // 箭头角度（30度）

          // 计算箭头两个点的位置
          const arrowX1 = currentX - arrowLength * Math.cos(angle - arrowAngle);
          const arrowY1 = currentY - arrowLength * Math.sin(angle - arrowAngle);
          const arrowX2 = currentX - arrowLength * Math.cos(angle + arrowAngle);
          const arrowY2 = currentY - arrowLength * Math.sin(angle + arrowAngle);

          // 绘制箭头
          this.overlayContext.beginPath();
          this.overlayContext.moveTo(currentX, currentY);
          this.overlayContext.lineTo(arrowX1, arrowY1);
          this.overlayContext.moveTo(currentX, currentY);
          this.overlayContext.lineTo(arrowX2, arrowY2);
          this.overlayContext.stroke();
        }
      },

      erase(x, y, tolerance = 10) {
        const canvas = document.getElementById('overlayCanvas');

        // 获取画布数据
        const imageData = this.overlayContext.getImageData(
          0,
          0,
          canvas.width,
          canvas.height
        );
        const data = imageData.data;

        // 获取擦除区域的像素数据
        const eraseRadius = this.brushSize + tolerance; // 扩大半径以确保擦除范围足够

        // 循环遍历每个像素
        for (let i = 0; i < data.length; i += 4) {
          const px = (i / 4) % canvas.width;
          const py = Math.floor(i / 4 / canvas.width);
          const dx = px - x;
          const dy = py - y;

          // 计算当前像素点到鼠标点的距离
          if (Math.sqrt(dx * dx + dy * dy) < eraseRadius) {
            data[i] = 255; // R
            data[i + 1] = 255; // G
            data[i + 2] = 255; // B
            data[i + 3] = 0; // A (透明度)
          }
        }

        // 更新画布
        this.overlayContext.putImageData(imageData, 0, 0);
      },

      stopDrawing() {
        if (!this.isDrawing) return;

        this.isDrawing = false;

        // 如果是绘制模式，结束当前路径
        if (this.currentMode === 'drawing') {
          this.overlayContext.closePath();
        }

        // 保存最终状态
        const canvas = document.getElementById('overlayCanvas');
        const finalState = this.overlayContext.getImageData(
          0,
          0,
          canvas.width,
          canvas.height
        );
        this.canvasHistory.push(finalState);
      },
      redrawCanvas() {
        const canvas = document.getElementById('overlayCanvas');
        if (canvas) {
          this.overlayContext.clearRect(0, 0, canvas.width, canvas.height);
        }

        if (this.canvasHistory.length > 0) {
          // 恢复最后的画布状态
          const lastState = this.canvasHistory[this.canvasHistory.length - 1];
          this.overlayContext.putImageData(lastState, 0, 0);
        }
      },
      undo() {
        this.selectedTool = 'undo';
        if (this.canvasHistory.length > 1) {
          // 确保至少有一个状态可以恢复
          const canvas = document.getElementById('overlayCanvas');

          // 保存当前状态到重做栈
          const currentState = this.overlayContext.getImageData(
            0,
            0,
            canvas.width,
            canvas.height
          );
          this.redoHistory.push(currentState);

          // 弹出最近的状态
          this.canvasHistory.pop(); // 移除当前状态
          const lastState = this.canvasHistory[this.canvasHistory.length - 1]; // 获取上一个状态

          // 清除当前画布
          this.overlayContext.clearRect(0, 0, canvas.width, canvas.height);

          // 恢复状态并立即重绘
          this.overlayContext.putImageData(lastState, 0, 0);
          this.draw('');
        }
      },
      redo() {
        if (this.redoHistory.length > 0) {
          // 保存当前状态到撤销栈
          const canvas = document.getElementById('overlayCanvas');
          const currentState = this.overlayContext.getImageData(
            0,
            0,
            canvas.width,
            canvas.height
          );
          this.canvasHistory.push(currentState);

          // 获取最近的还原状态
          const lastUndoState = this.redoHistory.pop();

          // 清除当前画布
          this.overlayContext.clearRect(0, 0, canvas.width, canvas.height);

          // 恢复状态并立即重绘
          this.overlayContext.putImageData(lastUndoState, 0, 0);
          this.draw('');
        }
      },
      showTextInput(event) {
        if (this.currentMode != 'text') return;

        const canvas = document.getElementById('overlayCanvas');
        const rect = canvas.getBoundingClientRect();

        // 计算相对于画布的位置
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        // 设置输入框的位置
        this.inputStyle = {
          position: 'absolute',
          left: `${x}px`,
          top: `${y}px`,
        };
        this.customText = ''; // 清空输入框内容
        this.showInput = true; // 显示输入框

        // 使用 nextTick 确保输入框显示后立即获得焦点
        this.$nextTick(() => {
          const inputElement = document.querySelector('.text-input');
          if (inputElement) {
            inputElement.focus(); // 设置焦点
          }
        });
      },
      addTextMarker(text, x, y) {
        if (!this.overlayContext) return;

        // 保存当前状态到历史记录
        const canvas = document.getElementById('overlayCanvas');
        const currentState = this.overlayContext.getImageData(
          0,
          0,
          canvas.width,
          canvas.height
        );
        this.canvasHistory.push(currentState);

        // 设置文本样式
        this.overlayContext.font = '15px Arial';
        this.overlayContext.fillStyle = this.brushColor;
        this.overlayContext.textBaseline = 'middle';

        // 绘制文本
        this.overlayContext.fillText(text, x, y);

        // 保存最终状态
        const finalState = this.overlayContext.getImageData(
          0,
          0,
          canvas.width,
          canvas.height
        );
        this.canvasHistory.push(finalState);
      },
      addTextMarkerOnBlur() {
        // if (this.customText && this.customText) {
        //   this.addTextMarker(
        //     this.customText,
        //     parseFloat(this.inputStyle.left),
        //     parseFloat(this.inputStyle.top) + 10
        //   );
        // }
        // this.showInput = false;
      },
      addTextMarkerOnEnter(event) {
        if (event.key === 'Enter' && this.customText) {
          // 计算相对于画布的位置
          this.addTextMarker(
            this.customText,
            parseFloat(this.inputStyle.left),
            parseFloat(this.inputStyle.top) + 10
          );
          this.showInput = false;
        }
      },
      handleInputBlur() {
        this.isInputActive = false;
        this.addTextMarkerOnBlur();
      },
      downloadImage() {
        this.currentMode = 'download';
        const myCanvas = document.getElementById('myCanvas');
        const myCanvas2 = document.getElementById('myCanvas2');
        const overlayCanvas = document.getElementById('overlayCanvas');

        const combinedCanvas = document.createElement('canvas');
        combinedCanvas.width = this.hbwidth;
        combinedCanvas.height = this.hbheight;
        const ctx = combinedCanvas.getContext('2d', {
          willReadFrequently: true,
        });
        // 设置背景颜色为黑色
        ctx.fillStyle = 'black';
        ctx.fillRect(0, 0, combinedCanvas.width, combinedCanvas.height);

        // 绘制第一个画布的内容
        ctx.drawImage(myCanvas, 0, 0);

        // 绘制第二个画布的内容，考虑其偏移位置
        const canvas2Offset = this.hbwidth / 2; // 使用与CSS中相同的偏移量
        ctx.drawImage(myCanvas2, canvas2Offset, 0);

        // 绘制标记画布的内容
        ctx.drawImage(overlayCanvas, 0, 0);

        try {
          // 将合成的画布转换为数据URL
          const imageDataURL = combinedCanvas.toDataURL('image/png');
          // 创建下载链接并触发下载
          const link = document.createElement('a');
          link.href = imageDataURL;
          link.download = 'combined_image.png';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } catch (error) {
          console.error('Error exporting canvas: ', error);
        }
      },

      clearOverlay() {
        this.currentMode = 'delel';
        this.selectedTool = 'clear';
        const overlayCanvas = document.getElementById('overlayCanvas');
        if (overlayCanvas) {
          const overlayContext = overlayCanvas.getContext('2d', {
            willReadFrequently: true,
          });
          overlayContext.clearRect(
            0,
            0,
            overlayCanvas.width,
            overlayCanvas.height
          );
        }
      },
      handleSearch(query) {
        this.optionsselect = [];
        this.state.markers.forEach((item) => {
          item.bsdata.forEach((items) => {
            if (items.text.toLowerCase().includes(query.toLowerCase())) {
              this.optionsselect.push({
                markingPointsId: items.markingPointsId,
                text: items.text,
              });
            }
          });
        });
      },
      changeselect(e) {
        // 重置一下当前选择
        this.changeimgclassfn('全部');
        this.changeimggroupfn('全部', true);
        this.state.markers.forEach((item) => {
          item.bsdata.forEach((items) => {
            if (items.markingPointsId == e) {
              let firstPart = item.medicineAtlasImgId.split(',')[0];
              this.state.hoveredMarker = items;
              this.tagdcom(Number(firstPart), '搜索');
            }
          });
        });
      },
      changecsd() {
        console.log('当前全选了');
        this.state.markers.forEach((item) => {
          item.bsdata.forEach((items) => {
            items.flag = this.allflag;
          });
        });

        this.anatomicStructure.forEach((jg) => {
          jg.flag = this.allflag;
        });
        this.saveMarkers();
        this.draw('');
      },
      async taskjp(item) {
        // 修改为name markingPointsId
        console.log('name', item);

        this.hoveredMarkerID = item.pointName;
        // 存储所有匹配的标记点
        const matchingMarkers = [];

        // 从左侧画布收集匹配的标记点
        // this.state.markers.forEach((item) => {
        //   item.bsdata.forEach((items) => {
        //     //  if (items.markingPointsId == item.pointName) {
        //     if (items.text == this.hoveredMarkerID) {
        //       let firstPart = item.medicineAtlasImgId.split(',')[0];

        //       console.log('存在1', firstPart);
        //       matchingMarkers.push({
        //         marker: items,
        //         imgId: Number(firstPart),
        //       });
        //     }
        //   });
        // });

        // 从右侧画布收集匹配的标记点
        this.state.markers2.forEach((item) => {
          item.bsdata.forEach((items) => {
            if (items.text == this.hoveredMarkerID) {
              // if (items.markingPointsId == id) {
              let firstPart = item.medicineAtlasImgId.split(',')[0];

              console.log('存在2', firstPart);
              matchingMarkers.push({
                marker: items,
                imgId: Number(firstPart),
              });
            }
          });
        });

        // 如果有匹配的标记点
        if (matchingMarkers.length > 0) {
          // 设置第一个匹配的标记点为当前悬停标记
          this.state.hoveredMarker = matchingMarkers[0].marker;

          // 切换到对应的图片
          await this.tagdcom(matchingMarkers[0].imgId);

          // 绘制左右画布

          this.draw('选中切换模式', 'right');
          this.draw('选中切换模式', 'left');
        }
      },
    },
  };
</script>

<style scoped>
  .text-input-container {
    /* 输入框的容器样式 */
    z-index: 99;
  }
  #myCanvas2 {
  }
  .text-input {
    padding: 5px;
    border: 1px solid #ccc;
  }
  #overlayCanvas {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2; /* 画板层 */
  }
  .bjbox {
    width: 100%;
    height: 172px;
  }
  .bjbox img {
    width: 100%;
    height: 172px;
  }
  .mainboxgj {
    display: flex;
    width: 100%;
    height: 100%;
  }

  .mainbottombox {
    width: 100%;
    height: 100%;
    display: flex;
  }

  .box {
    width: 100%;
    height: 667px;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-wrap: nowrap;
  }

  .mainsers {
    display: flex;
    align-items: center;
    padding-left: 15px;
    width: 100%;
    height: 5%;
    overflow: hidden;
    color: #333333;
    font-size: 14px;
    background: linear-gradient(180deg, #cfd3d9 0%, #b0b3b8 100%);
  }

  .gnbocdtop .arco-btn {
    margin: 0;
    /* margin: 5px 10px; */
  }
  .gnbocdtop {
    width: 100%;
    height: 15%;

    border-bottom: 2px solid #5a5a5a;
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
    overflow-y: auto;
  }
  .gnbocd {
    width: 100%;
    height: 75%;
    overflow: hidden;
    overflow-y: auto;

    display: flex;
    flex-direction: column;
  }
  .gnbocdname {
    font-size: 20px;
    color: #ffffff;
    padding: 10px;
  }

  #canvasContainer {
    position: relative;
  }

  .boxs {
    width: 300px;
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
  }

  .boxsitem {
    width: 130px;
    height: 130px;
    margin: 10px 25px;
    background: black;
  }
  .boxsitems {
    text-align: center;
  }

  .mainboxleft {
    width: 100%;
    height: 100%;
  }

  .gnbocd::-webkit-scrollbar {
    width: 5px;
    height: 5px;
  }

  .gnbocd::-webkit-scrollbar-track {
    width: 6px;
    background: rgba(#101f1c, 0.1);
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
  }

  .gnbocd::-webkit-scrollbar-thumb {
    background-color: rgba(133, 138, 148, 0.938);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
    transition: background-color 0.3s;
    cursor: pointer;
  }

  .gnbocd::-webkit-scrollbar-thumb:hover {
    background-color: rgba(144, 147, 153, 0.3);
  }

  .xugn {
    display: flex;
    /* justify-content: center; */
    align-items: center;
    margin: 5px 0;
    flex-wrap: wrap;
  }
  .xugname {
    width: 80px;
    color: #fff;
    font-size: 16px;
  }
  .xbanner {
    width: 100%;
    font-size: 16px;
    height: 40px;
    background-color: #fff;
    /* line-height: 40px; */
    padding-left: 10px;
    align-content: center;
  }

  /* 公共类 */
  /* 封装公共按钮类 */
  .tool {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .tool img.active {
    cursor: pointer;
    display: none;
  }

  .tool:hover img.normal,
  .tool.active img.normal {
    display: none;
  }

  .tool:hover img.active,
  .tool.active img.active {
    display: block;
  }
  .gnboxmain {
    padding: 0 15px;
  }
  .gnboxitem {
    height: 40px;
    background: #24292d;
    border-radius: 4px 4px 4px 4px;
    display: flex;
    align-items: center;
    color: #fff;
    padding: 0 12px;
    margin: 10px 0;
    font-size: 16px;
  }

  .zsclose {
    position: absolute;
    right: 20px;
    cursor: pointer;
  }

  .jpan {
    background-color: #424548;
    border-radius: 4px;
    /* padding: 10px 28px; */
    cursor: pointer;
    width: 108px;
    height: 38px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 5px 7px;
    text-align: center;
  }
  .jpanitem {
    width: 70%;
    color: #fff;
    text-wrap: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .jpan:hover {
    background-color: #409eff;
    border-radius: 4px;
    max-width: 108px;
  }
  .jpanac {
    background-color: #409eff;
    border-radius: 4px;
    max-width: 108px;
  }

  .mentbjacitem {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .colorts {
    position: absolute;
    z-index: 999;
    width: 35px;
    opacity: 0;
  }
  .hbcbox {
    width: 80px;
    height: 105px;
    background: #808080;
    border-radius: 10px 10px 10px 10px;
    position: absolute;
    top: 40px;
    right: -25px;
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 10px 0px;
    overflow: hidden;
  }

  .hbcitem {
    width: 50px;
    height: 0px;
    border-radius: 4px;
    margin: 5px 0;
  }
  .hbcbox :first-child {
    margin-top: 0px;
  }

  .sbodyd {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
  }

  .loader-container {
    text-align: center;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    position: fixed;
    top: 0px;
    left: 0px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    z-index: 99;
  }
  .loader {
    border: 8px solid #f3f3f3;
    border-top: 8px solid #3498db;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    animation: spin 1s linear infinite;
    margin: 20px auto;
  }
  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  .pd {
    font-family: Arial, sans-serif;
    color: #fff;
    font-size: 16px;
    margin-top: 10px;
  }
  /* 滚动条美化 */
  .beautifulScroll::-webkit-scrollbar {
    width: 5px;
    height: 5px;
    background: rgba(0, 0, 0, 0);
    border-radius: 5px;
  }

  .beautifulScroll::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0);
    border-radius: 5px;
  }

  .beautifulScroll::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background: #666666;
  }
  .fjx {
    position: absolute;
    height: 667px;
    width: 2px;
    background-color: #40495a;
    left: 50%;
    transform: translate(-50%, 0);
    top: 0;
  }
  .jpmentbox {
    height: 100%;
    width: 240px;
    padding: 0px 10px;
    overflow: hidden;
    overflow-y: auto;
  }
  .jpitem {
    width: 100%;
    height: 40px;
    border-bottom: 1px solid #9da4b3;
    line-height: 40px;
    padding-left: 10px;
    cursor: pointer;
    font-size: 16px;
    color: #101f1c;
    display: flex;
    align-items: center;
  }
  .jpitemacive {
    width: auto;
    height: 60%;
    overflow: hidden;
    border-radius: 10px;
    display: flex;
    align-items: center;

    padding: 0px 5px;
  }
  .jpitemacive:hover {
    background-color: #00ffe4;
  }
  .jpitemacivehover {
    background-color: #00ffe4;
  }
  .mainktbox {
    width: 100%;
    background-color: black;
    border-top: 2px solid #fff;
    height: 50px;
  }
  .maintopbox {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    border: 2px solid;
    border-image: linear-gradient(0deg, #b0bbcd, #ffffff) 10 10;
  }
  .mainktitembox {
    margin: 0 auto;
    width: 950px;
    height: 100%;
    background-color: #222222;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  .mainktitem {
    cursor: pointer;
  }
  .dctitlebox {
    position: absolute;
    left: 0px;
    top: 0px;
  }
  .dctitlebox img {
    width: 186px;
    height: 31px;
  }
  .dctitletext {
    font-size: 18px;
    color: #40495a;
    position: absolute;
    top: 1px;
    left: 10px;
    font-weight: 800;
  }
  .dctitlebox2 {
    position: absolute;
    left: 50%;
    top: 0px;
  }
  .mainktitem img {
    width: 20px;
    height: 20px;
  }
</style>
